﻿using System.Web.Mvc;
using System.Web.Security;

namespace KLS.PPDS.Utilities
{
    /// <summary>
    /// 
    /// </summary>
    public class AjaxAuthorizeAttribute : AuthorizeAttribute
    {
        public bool AuthorizeDisabled { get; set; }

        private bool IsValidate(AuthorizationContext filterContext)
        {
            if (!filterContext.HttpContext.Request.IsAuthenticated)
            {
                FormsAuthentication.SignOut();
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new JavaScriptResult { Script = "top.location.reload();" };
                }
                else
                {
                    filterContext.Result = new RedirectResult(FormsAuthentication.LoginUrl);
                }
                filterContext.HttpContext.User = null;
                return false;
            }

            
            return true;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //if (AuthorizeDisabled)
            //{
            //    base.HandleUnauthorizedRequest(filterContext);
            //}
            //else
            //{
            //    filterContext.Result 
            //}




            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JavaScriptResult
                                           {
                                               Script =
                                                   string.Format("top.location = '{0}'",
                                                                 FormsAuthentication.DefaultUrl)
                                           };
            }
            else
            {
                filterContext.Result = new RedirectResult(FormsAuthentication.DefaultUrl);
            }



        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {

          //  if (IsValidate(filterContext))
         //   {
                base.OnAuthorization(filterContext);

           // }
        }




    }
}
